題號:43 標題:Multiply Strings 難度:Medium
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
我的程式碼
class Solution {
    public String multiply(String num1, String num2) {
        String temp2 = new String();
        String temp3 = new String();
        String result = new String();
        int a,b,c=0,len1,len2,i,j,x=0;
        len1 = num1.length();
        len2 = num2.length();
        ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>();
        if(num1.equals("0")||num2.equals("0")){
            String temp4 = new String();
            temp4 = temp4+'0';
            return temp4;
        }
        for(i=len1-1;i>=0;i--){
            String temp = new String();
            a = num1.charAt(i)-48;
            c=0;
            for(j=len2-1;j>=0;j--){    
                b = num2.charAt(j)-48;
                //System.out.println("a,b:" +a +","+ b);
                c = a*b + c;
                //System.out.println("c:" +c);
                if(c > 9){
                    temp = temp + Integer.toString(c%10);
                    c = c/10;
                }else{
                    temp = temp + Integer.toString(c);
                    c = 0;
                }
            }
            if(c>0){
                temp = temp + Integer.toString(c);
            }
            for(j=i+1;j<len1;j++){
                    temp = '0' + temp;
            }
            System.out.println(temp);
            temp3 = "";
            x = 0;
            if(i!=len1-1){
                System.out.println(temp + ":" + temp2);
                for(j=0;j<temp.length();j++){
                    if(temp2.length()>j){
                        x = (temp.charAt(j)-48) + (temp2.charAt(j)-48)+x;
                    }else{
                        x= (temp.charAt(j)-48)+x;
                    }
                    if(x>9){
                        temp3 = temp3 + Integer.toString(x%10);
                        x = x/10;
                    }else{
                        temp3 = temp3 + Integer.toString(x);
                        x = 0;
                    }
                }
                if(x>0){
                    temp3 = temp3 + Integer.toString(x);
                }
                //System.out.println("temp3" + ":" + temp3);
                temp2 = "";
                temp2 = temp3;
            }else{
                temp2 = temp;
            }
        }
        
        
        for(i=temp2.length()-1;i>=0;i--){
            result = result + temp2.charAt(i);
        }
        
        return result;
    }
}
花比較久的時間
不能用BigInteger library,然後長度會超過long的長度,所以查了一下這種問題怎麼辦,我這題是用乘法直試邏輯寫得,ex三位數abc乘以二位數de,abc x de=e x abc + adc x d x 10
但因為有字串轉數字數字轉字串,所以超級麻煩,不過很有趣就是了,我寫得很開心
DAY23心得
今天心情不錯呢